<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 纤淼
 */
class XianmiaoController extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }
		
        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));

        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $isMobile = isMobile();

        //获取token
        $data = array();
        $data['appid'] = $this->config['mch_id'];
        $data['secretid'] = $this->config['signkey'];ksort($data);

        $res = curl_get($this->config['appsecret']."?".httpstr($data));
        $res = xmlToArray($res);
        $token = $res['token'];

        if(!$token){
            $this->showmessage('获取token失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $return = $this->orderadd( $parameter );

        $data = array();
        $data['version'] = '1.0';
        $data['charset'] = 'UTF-8';
        $data['sign_type'] = 'MD5';
        $data['mch_id'] = $this->config['mch_id'];
        $data['out_trade_no'] = $return['orderid'];
        $data['body'] = 'zf';
        //$data['attach'] = 'zf';
        $data['total_fee'] = $return['amount'] * 100;
        $data['mch_create_ip'] = getIP();
        $data['notify_url'] = $return['notifyurl'];
        //$data['time_start'] = time();
        //$data['time_expire'] = time() + 120;
        $data['nonce_str'] = md5(date("YmdHis",time()).mt_rand(10000,99999));

        ksort($data);
        $data['sign'] = strtoupper(md5(httpstr($data)."&key=".$this->config['signkey']));
        $res = $this->postXmlCurl($this->config['gateway']."?token=".$token , $this->arrayToXml($data));
        $res = xmlToArray($res);

        $code = $res['pay_info'];
        if(!$code){
            if($res['message']){
                $this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location: {$code}");
    }

    //数组转XML
    private function arrayToXml($arr){
        $xml = "<xml>";
        foreach ($arr as $key=>$val) {
            if ($key == 'total_fee'){
                $xml.="<".$key.">".$val."</".$key.">";
            }else{
                $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
            }
        }
        $xml.="</xml>";
        return $xml;
    }

    public function postXmlCurl($url,$xml,$second=10) {
        //设置header
        $header[] = "Content-type: text/xml";
        //初始化curl
        $ch = curl_init();
        //设置超时
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        curl_setopt($ch,CURLOPT_URL, $url);
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
        //设置header
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, TRUE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        //运行curl
        $data = curl_exec($ch);
        curl_close($ch);
        return $data;
    }


    //通知
    public function notifyurl(){
        //file_put_contents("a.txt",var_export($_POST,true)."\r\n\r\n");
        //file_put_contents("a.txt",var_export($_GET,true)."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", file_get_contents('php://input')."\r\n\r\n", FILE_APPEND);
        //file_put_contents("a.txt", date("Y-m-d H:i:s",time())."\r\n\r\n", FILE_APPEND);

        $p = $origin = file_get_contents('php://input');

        //$p = '<xml><transaction_id><![CDATA[77fd80bf34ab4fd58554fdd783af5f1d]]></transaction_id><charset><![CDATA[UTF-8]]></charset><nonce_str>1542171525110</nonce_str><sign><![CDATA[0BEAFF37DBE6D350D51B66F59A897D63]]></sign><fee_type><![CDATA[CNY]]></fee_type><mch_id><![CDATA[6000003]]></mch_id><version><![CDATA[1.0]]></version><pay_result>0</pay_result><out_trade_no><![CDATA[201811141258127485341]]></out_trade_no><total_fee>2000</total_fee><trade_type>WECHAT_WAP</trade_type><result_code>0</result_code><time_end><![CDATA[2018-11-14 12:58:45]]></time_end><sign_type><![CDATA[MD5]]></sign_type><status>0</status></xml>';

        $p = xmlToArray($p);

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['out_trade_no'];
        $find = M("Order")->where(array("pay_orderid"=>$orderid))->find();
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
            "server_return"=> $origin,
            "pay_orderid_rd"=>$p['transaction_id']
        ));

        /*
         * Array
            (
                [transaction_id] => 77fd80bf34ab4fd58554fdd783af5f1d
                [charset] => UTF-8
                [nonce_str] => 1542171525110
                [sign] => 0BEAFF37DBE6D350D51B66F59A897D63
                [fee_type] => CNY
                [mch_id] => 6000003
                [version] => 1.0
                [pay_result] => 0
                [out_trade_no] => 201811141258127485341
                [total_fee] => 2000
                [trade_type] => WECHAT_WAP
                [result_code] => 0
                [time_end] => 2018-11-14 12:58:45
                [sign_type] => MD5
                [status] => 0
            )
         */

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>'Xianmiao']);

        $sign = $p['sign'];
        unset($p['sign']);

        ksort($p);

        $sign2 = strtoupper(md5(httpstr($p)."&key=".$this->config['signkey']));

        /*
        echo '<pre/>'; print_r($p);
        echo "sign: " .$sign ."<br/>";
        echo "sign2:".$sign2."<br/>";
        */
        if($sign != $sign2){
            exit("sign_wrong");
        }

        if($p['status'] != 0 || $p['result_code'] != 0){
            exit("pay_fail");
        }

        $this->async($find['pay_orderid'],'success');
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}